package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.Goods;
import com.rongke.model.GoodsPage;
import com.rongke.model.GoodsRecommend;
import com.rongke.service.GoodsRecommendService;
import com.rongke.service.GoodsService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @version : Ver 1.0
 * @GoodsRecommendController
 * @商品推荐Controller
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "/api/goodsRecommend")
@Transactional
public class GoodsRecommendController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private GoodsRecommendService goodsRecommendService;
    @Autowired
    private GoodsService goodsService;


    /**
     * @param goodsRecommend
     * @return 返回值JsonResp
     * @添加商品推荐
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addGoodsRecommend(@RequestBody GoodsRecommend goodsRecommend) {
        log.debug("添加商品推荐");
        if(null==goodsRecommend.getGoodsId()||null==goodsRecommend.getRecGoodsId())
            return JsonResp.toFail("server:商品id和推荐商品id不能为空");
        goodsRecommend.setGmtDatetime(new Date());
        goodsRecommendService.insert(goodsRecommend);
        return JsonResp.ok(goodsRecommend);
    }

    /**
     * @param recList
     * @return
     * @批量添加推荐商品
     */
    @RequestMapping(value = "/addRecGoodsBatch", method = RequestMethod.POST)
    public JsonResp addRecGoodsBatch(@RequestBody List<GoodsRecommend> recList) {
        log.debug("批量添加推荐商品");
        if (null == recList || recList.size() == 0)
            return JsonResp.toFail("server:添加的推荐商品不能为空");
        for (GoodsRecommend gr : recList){
            if(null==gr.getGoodsId()||null==gr.getRecGoodsId()){
                recList.remove(gr);
            }else{
                gr.setGmtDatetime(new Date());
            }
        }
        goodsRecommendService.insertBatch(recList);
        return JsonResp.ok(recList);

    }

    /**
     * @param recList
     * @return
     * @批量删除推荐商品
     */
    @RequestMapping(value = "/deleteRecGoodsBatch", method = RequestMethod.POST)
    public JsonResp deleteRecGoodsBatch(@RequestBody List<GoodsRecommend> recList) {
        log.debug("批量删除推荐商品");
        if (null == recList || recList.size() == 0)
            return JsonResp.toFail("server:要删除的推荐商品不能为空");
        for (GoodsRecommend gr : recList) {
            EntityWrapper<GoodsRecommend> ew = new EntityWrapper<>(gr);
            goodsRecommendService.delete(ew);
        }
        return JsonResp.ok(recList);
    }

    /**
     * @param goodsRecommend
     * @return 返回值JsonResp
     * @修改商品推荐
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateGoodsRecommend(@RequestBody GoodsRecommend goodsRecommend) {
        log.debug("修改商品推荐");
        goodsRecommend.setUptDatetime(new Date());
        goodsRecommendService.updateById(goodsRecommend);
        return JsonResp.ok(goodsRecommend);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找商品推荐
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectGoodsRecommend(Long id) {
        log.debug("查找商品推荐");
        GoodsRecommend goodsRecommend = goodsRecommendService.selectById(id);
        return JsonResp.ok(goodsRecommend);
    }

    /**
     * @param goodsRecommend
     * @return 返回值JsonResp
     * @根据条件查找商品推荐
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectGoodsRecommendByCondition(@RequestBody GoodsRecommend goodsRecommend) {
        log.debug("根据条件查找商品推荐");
        if (goodsRecommend == null)
            return JsonResp.toFail("参数不能为空");
        List<GoodsRecommend> goodsRecommendList = goodsRecommendService.selectByCondition(goodsRecommend);
        return JsonResp.ok(goodsRecommendList);
    }

    /**
     * @param goodsPage
     * @return
     * @获取某商品的发布在售的推荐商品列表
     */
    @RequestMapping(value = "/getGoodsRecListByGoodsId", method = RequestMethod.POST)
    public JsonResp getGoodsRecListByGoodsId(@RequestBody GoodsPage goodsPage) {
        log.debug("获取某商品的发布在售的推荐商品列表");
        Goods goods = goodsPage.getGoods();
        Page page = goodsPage.getPage();
        if (null == goodsPage.getGoods() || null == goods.getId() || null == page)
            return JsonResp.toFail("参数不能为null");
        EntityWrapper<GoodsRecommend> ewgr = new EntityWrapper();
        ewgr.eq("goods_id", goods.getId());
        //先从推荐表获取推荐商品列表
        List<GoodsRecommend> recommendList = goodsRecommendService.selectList(ewgr);
        EntityWrapper<Goods> ew = new EntityWrapper<>();
        Page<Goods> gdPage = new Page<>(page.getCurrent(), page.getSize());
        if (recommendList.size() > 0) {
            List<Long> idList = new ArrayList<>();
            //取出推荐商品的id集合
            for (GoodsRecommend rec : recommendList) {
                if (null != rec.getRecGoodsId())
                    idList.add(rec.getRecGoodsId());
            }
            ew.in("id", idList);
            gdPage = goodsService.selectPage(page, ew);
        }
        //推荐商品的个数
        Integer recLength = gdPage.getRecords().size();
        if (recLength < page.getSize()) {
            Integer classifyId = goodsService.selectById(goods.getId()).getClassifyId();
            EntityWrapper<Goods> gew = new EntityWrapper<>();
            gew.eq("classify_id", classifyId);
            gew.notIn("id",goods.getId());
            //最后返回分页结果的records
            List<Goods> allRecList = new ArrayList<>();
            if (recLength > 0) {
                allRecList.addAll(gdPage.getRecords());
                //获取已推荐商品id数组
                List<Long> ids = new ArrayList<>();
                for (Goods gs : gdPage.getRecords()) {
                    ids.add(gs.getId());
                }
                gew.notIn("id", ids);
            }
            //待补足的推荐商品数
            int leftSize = page.getSize() - recLength;
            Page<Goods> tailRecPage = goodsService.selectPage(new Page<Goods>(1, leftSize), gew);
            List<Goods> recList = tailRecPage.getRecords();

            allRecList.addAll(recList);

//            gdPage.getRecords().addAll(recList);
            gdPage.setRecords(allRecList);
        }
        if(!gdPage.getRecords().isEmpty()){
            gdPage.getRecords().forEach(e->{
                goodsService.fetchGoodsInventoryStatus(e);//判断库存状态
            });
        }
        return JsonResp.ok(gdPage);
    }

    /**
     * 后台获取某商品的发布在售的推荐商品列表
     *
     * @return
     */
    @RequestMapping(value = "/getAdminGoodsRecListByGoodsId", method = RequestMethod.POST)
    public JsonResp getAdminGoodsRecListByGoodsId(@RequestBody GoodsPage goodsPage) {
        log.debug("后台获取某商品的发布在售的推荐商品列表");
        Goods goods = goodsPage.getGoods();
        Page page = goodsPage.getPage();
        if (null == goodsPage.getGoods() || null == goods.getId() || null == page)
            return JsonResp.toFail("参数不能为null");
        EntityWrapper<GoodsRecommend> ewgr = new EntityWrapper();
        ewgr.eq("goods_id", goods.getId());
        //先从推荐表获取推荐商品列表
        List<GoodsRecommend> recommendList = goodsRecommendService.selectList(ewgr);
        if (recommendList.size() == 0)
            return JsonResp.ok();
        List<Long> idList = new ArrayList<>();
        //取出推荐商品的id集合
        for (GoodsRecommend rec : recommendList) {
            if (null != rec.getRecGoodsId())
                idList.add(rec.getRecGoodsId());
        }
        EntityWrapper<Goods> ew = new EntityWrapper<>();
        ew.in("id", idList);
        //搜索
        if (null != goodsPage.getSearchText())
            ew.like("goods_name", goodsPage.getSearchText());
        Page<Goods> gdPage = goodsService.selectPage(page, ew);
        return JsonResp.ok(gdPage);
    }

    /**
     * @param goodsPage
     * @return
     * @后台推荐管理分页获取可推荐的商品(可按商品分类，分组等)
     */
    @RequestMapping(value = "/getUnRecedGoodsListWithCategory", method = RequestMethod.POST)
    public JsonResp getUnRecedGoodsListWithCategory(@RequestBody GoodsPage goodsPage) {
        log.debug("后台推荐管理分页获取可添加推荐的商品(可按商品分类，分组等)");
        Goods goods = goodsPage.getGoods();
        Page page = goodsPage.getPage();
        if (null == goods.getGoodsType())
            return JsonResp.toFail("产品线参数不能为空");
        if (null == page)
            return JsonResp.toFail("参数不能为空");
        if (null == goods.getId()) {
            return JsonResp.ok();
        }


        EntityWrapper<Goods> ew = new EntityWrapper<>();
        //已发布的该产品线下在售的商品（不包括自身和已推荐商品）
        ew.notIn("id", goods.getId())
                .eq("goods_status", 2)
                .eq("goods_type", goods.getGoodsType());
        ;
        if (null != goods.getClassifyId())
            ew.eq("classify_id", goods.getClassifyId());
        if (null != goods.getIndexGroupId())
            ew.eq("index_group_id", goods.getIndexGroupId());

        //排除已添加推荐的商品
        EntityWrapper<GoodsRecommend> ewgr = new EntityWrapper();
        ewgr.eq("goods_id", goods.getId());
        //先从推荐表获取推荐商品列表
        List<GoodsRecommend> recommendList = goodsRecommendService.selectList(ewgr);
        if (recommendList.size() > 0) {
            List<Long> idList = new ArrayList<>();
            //取出推荐商品的id集合
            for (GoodsRecommend rec : recommendList) {
                if (null != rec.getRecGoodsId())
                    idList.add(rec.getRecGoodsId());
            }
            ew.notIn("id", idList);
        }

        //搜索
        if (null != goodsPage.getSearchText())
            ew.like("goods_name", goodsPage.getSearchText());
        Page<Goods> gdPage = goodsService.selectPage(page, ew);
        gdPage.setOrderByField("classify_id");
        return JsonResp.ok(gdPage);
    }

}
